package com.example.controller;

import com.example.utils.constant.AirwallexConstant;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Description: 公共请求控制器
 * @Auther: Swain
 * @Date: 2021/1/11 16:48
 * @Version 1.0.0
 */
@Log4j2
@ApiIgnore
@Controller
public class CommonController {

    /**
     * @param
     * @return java.lang.String
     * @Description 跳转swaggerUI界面
     * @Author swain
     * @Date 2021/1/13
     */
    @RequestMapping("/")
    public String swagger() {
        return "redirect:/document.html";
    }


    /**
     * @param
     * @return java.lang.String
     * @Description 跳转swaggerUI界面
     * @Author swain
     * @Date 2021/1/13
     */
    @PostMapping("/airwallex/callback")
    @ResponseBody
    public String callbackForAirwallex(HttpServletRequest request, @RequestBody String payload,
        HttpServletResponse response) {
        String responseBody = "";
        StringBuilder valueToDigest = new StringBuilder();
        // Get the timestamp from header
        String timestamp = request.getHeader("x-timestamp");
        valueToDigest.append(timestamp);
        valueToDigest.append(payload);
        // Get the signature from header
        String signature = request.getHeader("x-signature");
        // Get your secret
        String secret = AirwallexConstant.SECRET;
        if (HmacUtils.hmacSha256Hex(secret, valueToDigest.toString()).equals(signature)) {
            // Do something with event

            System.out.println("hello baby");

            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // Invalid signature
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            responseBody = "failed to verify the signature";
        }
        return responseBody;
    }

}
